document.addEventListener('DOMContentLoaded', function() {
    // 获取DOM元素
    const videoPlayerContainer = document.getElementById('video-player-container');
    const videoPlayer = document.getElementById('video-player');
    const noVideoMessage = document.getElementById('no-video-message');
    const currentPlaybackInfo = document.getElementById('current-playback-info');
    const currentVideoTitle = document.getElementById('current-video-title');
    const currentVideoDuration = document.getElementById('current-video-duration');
    const currentVideoSize = document.getElementById('current-video-size');
    const videosTableBody = document.getElementById('videos-table-body');
    const videoSearch = document.getElementById('video-search');
    const sortOption = document.getElementById('sort-option');
    const refreshBtn = document.getElementById('refresh-btn');
    const goUpBtn = document.getElementById('go-up-btn');
    const loadingIndicator = document.getElementById('loading-indicator');
    const emptyState = document.getElementById('empty-state');
    const currentPathDisplay = document.getElementById('current-path-display');
    const toggleFullscreenBtn = document.getElementById('toggle-fullscreen');
    const refreshPlayerBtn = document.getElementById('refresh-player');
    
    // 当前路径变量（默认为根目录）
    let currentPath = '';
    // 路径历史记录，用于返回上一级
    const pathHistory = [];
    // 当前视频索引
    let currentVideoIndex = -1;
    let currentVideoInfo = null;
    let videoList = [];
    
    // 初始化页面
    loadVideosList(true);
    
    // 绑定事件监听器
    if (refreshBtn) {
        refreshBtn.addEventListener('click', function() {
            loadVideosList(true);
        });
    }
    
    if (videoSearch) {
        videoSearch.addEventListener('keypress', function(e) {
            if (e.key === 'Enter') {
                loadVideosList();
            }
        });
        
        // 防抖搜索
        videoSearch.addEventListener('input', debounce(function() {
            loadVideosList();
        }, 500));
    }
    
    if (sortOption) {
        sortOption.addEventListener('change', function() {
            loadVideosList();
        });
    }
    
    if (goUpBtn) {
        goUpBtn.addEventListener('click', goToParentDirectory);
    }
    
    if (toggleFullscreenBtn) {
        toggleFullscreenBtn.addEventListener('click', toggleFullscreen);
    }
    
    if (refreshPlayerBtn) {
        refreshPlayerBtn.addEventListener('click', function() {
            if (videoPlayer.src) {
                videoPlayer.load();
                showNotification('播放器已刷新', 'success');
            }
        });
    }
    
    // 监听视频播放器错误
    videoPlayer.addEventListener('error', function() {
        showNotification('视频播放错误，请尝试其他视频', 'error');
        resetPlayer();
    });
    
    // 监听视频元数据加载完成事件
    videoPlayer.addEventListener('loadedmetadata', function() {
        updateVideoDuration();
    });
    
    // 监听视频播放完成事件，自动播放下一个视频
    videoPlayer.addEventListener('ended', function() {
        playNextVideo();
    });
    
    // 为视频播放器添加双击全屏功能
    videoPlayer.addEventListener('dblclick', toggleFullscreen);
    
    // 为上一个/下一个视频按钮添加事件监听
    document.getElementById('prev-video-btn').addEventListener('click', playPreviousVideo);
    document.getElementById('next-video-btn').addEventListener('click', playNextVideo);
    
    // 防抖函数实现
    function debounce(func, wait) {
        let timeout;
        return function() {
            const context = this;
            const args = arguments;
            clearTimeout(timeout);
            timeout = setTimeout(() => func.apply(context, args), wait);
        };
    }
    
    // 通知函数实现
    window.showNotification = function(message, type = 'info') {
        // 简单实现，可根据需要替换为更复杂的通知组件
        const notification = document.createElement('div');
        notification.className = `fixed bottom-4 right-4 px-4 py-2 rounded shadow-lg ${
            type === 'error' ? 'bg-red-500 text-white' :
            type === 'success' ? 'bg-green-500 text-white' :
            'bg-blue-500 text-white'
        }`;
        notification.textContent = message;
        document.body.appendChild(notification);
        
        setTimeout(() => {
            notification.style.opacity = '0';
            notification.style.transition = 'opacity 0.3s ease';
            setTimeout(() => notification.remove(), 300);
        }, 3000);
    };
    
    // 加载视频列表
    function loadVideosList(forceRefresh = false) {
        // 显示加载状态
        showLoading(true);
        
        // 获取查询参数
        const searchQuery = videoSearch.value.trim();
        const sortValue = sortOption.value;
        
        // 更新当前路径显示
        updateCurrentPathDisplay();
        
        // 构建API URL
        let apiUrl = `/api/local-cinema/videos?sort=${encodeURIComponent(sortValue)}`;
        if (searchQuery) {
            apiUrl += `&q=${encodeURIComponent(searchQuery)}`;
        }
        if (currentPath) {
            apiUrl += `&path=${encodeURIComponent(currentPath)}`;
        }
        
        // 发送请求到API
        fetch(apiUrl)
            .then(response => {
                if (!response.ok) {
                    throw new Error(`HTTP错误，状态码: ${response.status}`);
                }
                return response.json();
            })
            .then(data => {
                showLoading(false);
                
                if (data.success && Array.isArray(data.data)) {
                      videoList = data.data;
                      renderVideosList(data.data);
                  } else {
                    renderEmptyState();
                    showNotification(data.message || '加载视频列表失败', 'error');
                }
            })
            .catch(error => {
                console.error('加载视频列表失败:', error);
                showLoading(false);
                renderEmptyState();
                showNotification('加载视频列表失败: ' + error.message, 'error');
            });
    }
    
    // 渲染视频列表
    function renderVideosList(videos) {
        // 清空表格内容
        videosTableBody.innerHTML = '';
        
        if (videos.length === 0) {
            renderEmptyState();
            return;
        }
        
        // 隐藏空状态
        emptyState.classList.add('hidden');
        
        // 添加视频到表格
        videos.forEach(video => {
            const row = document.createElement('tr');
            row.className = 'hover:bg-gray-50 transition-colors';
            
            // 判断是否为文件夹或视频文件
            const isFolder = !video.is_file;
            const isVideo = video.is_file && video.is_video;
            
            // 格式化修改时间
            const lastModified = new Date(video.last_modified);
            const formattedDate = lastModified.toLocaleString('zh-CN', {
                year: 'numeric',
                month: '2-digit',
                day: '2-digit',
                hour: '2-digit',
                minute: '2-digit'
            });
            
            // 格式化文件大小
            let formattedSize = '';
            if (video.size !== null) {
                if (video.size < 1024) {
                    formattedSize = `${video.size} B`;
                } else if (video.size < 1048576) {
                    formattedSize = `${(video.size / 1024).toFixed(2)} KB`;
                } else if (video.size < 1073741824) {
                    formattedSize = `${(video.size / 1048576).toFixed(2)} MB`;
                } else {
                    formattedSize = `${(video.size / 1073741824).toFixed(2)} GB`;
                }
            }
            
            // 构建行内容
            row.innerHTML = `
                <td class="py-3 px-4">
                    <div class="flex items-center">
                        <div class="file-icon ${isFolder ? 'folder' : 'video'}">
                            <i class="fa ${isFolder ? 'fa-folder' : 'fa-file-video-o'}"></i>
                        </div>
                        <span class="truncate max-w-[200px]">${video.name}</span>
                    </div>
                </td>
                <td class="py-3 px-4">
                    <span class="text-sm text-gray-600">${isFolder ? '文件夹' : '视频文件'}</span>
                </td>
                <td class="py-3 px-4">
                    <span class="text-sm text-gray-600">${formattedSize}</span>
                </td>
                <td class="py-3 px-4">
                    <span class="text-sm text-gray-600">${formattedDate}</span>
                </td>
                <td class="py-3 px-4">
                    <div class="flex space-x-2">
                        ${isFolder ? `
                            <button class="action-btn open" data-path="${video.path}">
                                <i class="fa fa-folder-open mr-1"></i> 打开
                            </button>
                        ` : isVideo ? `
                            <button class="action-btn play" data-path="${video.path}">
                                <i class="fa fa-play mr-1"></i> 播放
                            </button>
                        ` : ''}
                    </div>
                </td>
            `;
            
            // 添加到表格
            videosTableBody.appendChild(row);
        });
        
        // 绑定按钮事件
        bindTableEvents();
    }
    
    // 绑定表格按钮事件
    function bindTableEvents() {
        // 播放按钮事件
        document.querySelectorAll('.action-btn.play').forEach(btn => {
            btn.addEventListener('click', function() {
                const videoPath = this.getAttribute('data-path');
                playVideo(videoPath);
            });
        });
        
        // 打开文件夹按钮事件
        document.querySelectorAll('.action-btn.open').forEach(btn => {
            btn.addEventListener('click', function() {
                const folderPath = this.getAttribute('data-path');
                navigateToFolder(folderPath);
            });
        });
    }
    
    // 播放视频
    function playVideo(videoPath) {
        // 构建视频播放URL
        const videoUrl = `/api/local-cinema/stream?path=${encodeURIComponent(videoPath)}`;
        
        // 显示播放器，隐藏提示信息
        videoPlayer.classList.remove('hidden');
        noVideoMessage.classList.add('hidden');
        currentPlaybackInfo.classList.remove('hidden');
        
        // 设置视频源并加载
        videoPlayer.src = videoUrl;
        videoPlayer.load();
        
        // 尝试自动播放视频，处理可能的自动播放限制
        videoPlayer.play().catch(error => {
            console.log('自动播放被阻止，用户需要交互才能播放:', error);
            // 这里可以选择显示一个播放按钮，让用户点击开始播放
        });
        
        // 更新视频信息
        const videoName = videoPath.split('/').pop();
        currentVideoTitle.textContent = videoName;
        
        // 获取并显示视频详细信息
        fetch(`/api/local-cinema/video-info?path=${encodeURIComponent(videoPath)}`)
            .then(response => response.json())
            .then(data => {
                if (data.success && data.data) {
                    currentVideoSize.textContent = data.data.size_formatted;
                }
            })
            .catch(error => {
                console.error('获取视频信息失败:', error);
            });
        
        // 更新当前视频索引
        if (videoList.length > 0) {
            currentVideoIndex = videoList.findIndex(video => video.path === videoPath);
        }
        
        // 滚动到播放器区域
        videoPlayerContainer.scrollIntoView({ behavior: 'smooth', block: 'start' });
    }
    
    // 更新视频时长显示
    function updateVideoDuration() {
        const duration = videoPlayer.duration;
        if (!isNaN(duration)) {
            const minutes = Math.floor(duration / 60);
            const seconds = Math.floor(duration % 60);
            currentVideoDuration.textContent = `时长: ${minutes}:${seconds.toString().padStart(2, '0')}`;
        }
    }
    
    // 重置播放器状态
    function resetPlayer() {
        videoPlayer.src = '';
        videoPlayer.classList.add('hidden');
        noVideoMessage.classList.remove('hidden');
        currentPlaybackInfo.classList.add('hidden');
        currentVideoTitle.textContent = '';
        currentVideoDuration.textContent = '';
        currentVideoSize.textContent = '';
    }
    
    // 导航到文件夹
    function navigateToFolder(folderPath) {
        // 保存当前路径到历史记录
        if (currentPath) {
            pathHistory.push(currentPath);
        }
        
        // 更新当前路径
        currentPath = folderPath;
        
        // 加载新路径的视频列表
        loadVideosList();
        
        // 更新返回按钮状态
        updateGoUpButtonState();
    }
    
    // 返回上一级目录
    function goToParentDirectory() {
        const currentPathDisplayText = currentPathDisplay.textContent;
        
        // 检查当前路径是否已经是根目录 /app/skit
        if (currentPathDisplayText === '/app/skit') {
            showNotification('已到达根目录，无法继续返回。', 'info');
            return;
        }
        
        if (pathHistory.length > 0) {
            currentPath = pathHistory.pop();
            loadVideosList();
        } else if (currentPath) {
            // 如果没有历史记录但当前不在根目录，尝试返回父目录
            const parentPath = currentPath.substring(0, currentPath.lastIndexOf('/'));
            currentPath = parentPath || '';
            loadVideosList();
        }
        
        // 更新返回按钮状态
        updateGoUpButtonState();
    }
    
    // 播放上一个视频
    function playPreviousVideo() {
        if (videoList.length > 0 && currentVideoIndex > 0) {
            // 查找前一个视频文件
            let prevIndex = currentVideoIndex - 1;
            while (prevIndex >= 0) {
                const prevItem = videoList[prevIndex];
                if (prevItem.is_file && prevItem.is_video) {
                    playVideo(prevItem.path);
                    currentVideoIndex = prevIndex;
                    return;
                }
                prevIndex--;
            }
            showNotification('没有找到前一个视频文件。', 'info');
        } else {
            showNotification('已经是第一个视频了。', 'info');
        }
    }
    
    // 播放下一个视频
    function playNextVideo() {
        if (videoList.length > 0 && currentVideoIndex < videoList.length - 1) {
            // 查找下一个视频文件
            let nextIndex = currentVideoIndex + 1;
            while (nextIndex < videoList.length) {
                const nextItem = videoList[nextIndex];
                if (nextItem.is_file && nextItem.is_video) {
                    playVideo(nextItem.path);
                    currentVideoIndex = nextIndex;
                    return;
                }
                nextIndex++;
            }
            showNotification('没有找到下一个视频文件。', 'info');
        } else {
            showNotification('已经是最后一个视频了。', 'info');
        }
    }
    
    // 更新返回按钮状态
    function updateGoUpButtonState() {
        if (goUpBtn) {
            goUpBtn.disabled = pathHistory.length === 0 && !currentPath;
            if (goUpBtn.disabled) {
                goUpBtn.classList.add('opacity-50', 'cursor-not-allowed');
            } else {
                goUpBtn.classList.remove('opacity-50', 'cursor-not-allowed');
            }
        }
    }
    
    // 更新当前路径显示
    function updateCurrentPathDisplay() {
        if (currentPathDisplay) {
            const displayPath = currentPath ? currentPath : '/app/skit';
            currentPathDisplay.textContent = displayPath;
        }
    }
    
    // 切换全屏模式
    function toggleFullscreen() {
        if (!document.fullscreenElement) {
            // 进入全屏
            if (videoPlayerContainer.requestFullscreen) {
                videoPlayerContainer.requestFullscreen();
            } else if (videoPlayerContainer.mozRequestFullScreen) {
                videoPlayerContainer.mozRequestFullScreen();
            } else if (videoPlayerContainer.webkitRequestFullscreen) {
                videoPlayerContainer.webkitRequestFullscreen();
            } else if (videoPlayerContainer.msRequestFullscreen) {
                videoPlayerContainer.msRequestFullscreen();
            }
        } else {
            // 退出全屏
            if (document.exitFullscreen) {
                document.exitFullscreen();
            } else if (document.mozCancelFullScreen) {
                document.mozCancelFullScreen();
            } else if (document.webkitExitFullscreen) {
                document.webkitExitFullscreen();
            } else if (document.msExitFullscreen) {
                document.msExitFullscreen();
            }
        }
    }
    
    // 显示/隐藏加载状态
    function showLoading(show) {
        if (loadingIndicator) {
            loadingIndicator.classList.toggle('hidden', !show);
        }
        
        if (videosTableBody) {
            videosTableBody.classList.toggle('hidden', show);
        }
        
        if (emptyState) {
            emptyState.classList.toggle('hidden', show);
        }
    }
    
    // 显示空状态
    function renderEmptyState() {
        videosTableBody.innerHTML = '';
        emptyState.classList.remove('hidden');
    }
    
    // 初始化返回按钮状态
    updateGoUpButtonState();
});